package com.stu.book.java8sz2.char10;

import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;

/**
 * @author zhuzi
 * 2022/6/22 11:29
 */
public class DemoFlatMap {

    @Test
    public void flapMap() {
        Insurance insurance = new Insurance("平安保险");
        Car car = new Car(Optional.of(insurance));
        Person person = new Person(Optional.ofNullable(car));

        String s = Optional.ofNullable(person).flatMap(Person::getCar).flatMap(Car::getInsurance).map(Insurance::getName).orElse(RandomStringUtils.randomAlphabetic(5));
        System.out.println(s);
    }

    @Data
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Person {

        private Optional<Car> car;

        public Optional<Car> getCar() {
            return car;
        }
    }

    @Data
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Car {

        private Optional<Insurance> insurance;

        public Optional<Insurance> getInsurance() {
            return insurance;
        }
    }

    @Data
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Insurance {

        private String name;

        public String getName() {
            return name;
        }
    }
}
